package com.lj.common_web.config;

import com.lj.common.config.DataScopeHolder;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * @author luojing
 * @since 2025/8/8 15:12
 * 数据范围过滤器
 * 因为提供服务的模块是不包含web相关依赖的，无法感知当前请求来自那个api接口，使用ThreadLocal来解决这一问题
 */
@Component
@WebFilter(urlPatterns = "/**", filterName = "dataScopeFilter")
public class DataScopeFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        try {
            DataScopeHolder.set(request.getServletPath());
            // 继续执行
            filterChain.doFilter(request, response);
        } finally {
            // 执行完成 清楚
            DataScopeHolder.clear();
        }
    }
}
